import 'dart:convert';

import 'package:card_swiper/card_swiper.dart';
import 'package:chewie/chewie.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pineapple_flutter/entity/movie_commnets_entity.dart';
import 'package:pineapple_flutter/entity/movie_detail_entity.dart';
import 'package:pineapple_flutter/routers/routers.dart';
import 'package:pineapple_flutter/utils/singleton_manager.dart';

import '../config/config.dart';
import '../http/api.dart';
import '../views/vedio_controller.dart';

class MovieDetails extends StatefulWidget {
  String movieId;

  MovieDetails({Key? key, this.movieId = ""}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MovieDetailsState();
}

class _MovieDetailsState extends State<MovieDetails> {
  //
  getYanyuan(int index) {
    return Container(
      padding: EdgeInsets.fromLTRB(8.w, 0, 8.w, 0),
      width: 225.w,
      child: Column(
        children: [
          InkWell(
            onTap: () {
              List newlist = detailEntity.item.plotsWords.map((e) {
                return '${Config.baseUrl}${e.imgUrl}';
              }).toList();
              SingletonManager.instance.galleryItems = newlist;
              Routes.navigateTo(context, Routes.photoPreview,
                  params: {'defaultImage': index.toString()});
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(3),
              child: Image.network(
                "${Config.baseUrl}${detailEntity.item.plotsWords[index].imgUrl}",
                fit: BoxFit.fill,
                width: double.infinity,
                height: 290.w,
              ),
            ),
          ),
          const Padding(padding: EdgeInsets.all(2)),
          Text(
            '${detailEntity.item.plotsWords[index].actorRole}:${detailEntity.item.plotsWords[index].autor}',
            softWrap: false,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: (Config.colorText1), fontSize: 25.sp),
          ),
        ],
      ),
    );
  }

  //
  getJuzhao(int index) {
    return Container(
      padding: EdgeInsets.fromLTRB(8.w, 0, 8.w, 0),
      width: 225.w,
      child: Column(
        children: [
          InkWell(
            onTap: () {
              List newlist = detailEntity.item.plotsImg.map((e) {
                return '${Config.baseUrl}${e.imgUrl}';
              }).toList();
              SingletonManager.instance.galleryItems = newlist;
              Routes.navigateTo(context, Routes.photoPreview,
                  params: {'defaultImage': index.toString()});
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(3),
              child: Image.network(
                '${Config.baseUrl}${detailEntity.item.plotsImg[index].imgUrl}',
                fit: BoxFit.cover,
                width: double.infinity,
                height: 310.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  //
  getCommentList(int index) {
    return Container(
      padding: EdgeInsets.fromLTRB(0.w, 0, 10.w, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(23.w),
                child: Image.network(
                  '${Config.baseUrl}${commnetsEntity.list[index].headicon}',
                  fit: BoxFit.fill,
                  width: 44.w,
                  height: 44.w,
                  errorBuilder: (ctx, err, stackTrace) => Image.asset(
                    'assets/images/launcher.png', //默认显示图片
                    width: 44.w,
                    height: 44.w,
                  ),
                ),
              ),
              Padding(padding: EdgeInsets.all(10.w)),
              Text(commnetsEntity.list[index].nickname,
                  style:
                      TextStyle(color: (Config.colorText1), fontSize: 32.sp)),
            ],
          ),
          SizedBox(
            width: 660.w,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(padding: EdgeInsets.all(8.w)),
                Text(
                  commnetsEntity.list[index].content,
                  style: TextStyle(color: (Config.colorText1), fontSize: 25.sp),
                ),
                Padding(padding: EdgeInsets.all(8.w)),
                Text(
                  commnetsEntity.list[index].startTime,
                  style: TextStyle(color: (Config.colorText3), fontSize: 18.sp),
                ),
              ],
            ),
          ),
          Padding(padding: EdgeInsets.all(15.w)),
          Divider(
            color: Config.colorDivider,
            height: 2.w,
            thickness: 1.w,
          ),
          Padding(padding: EdgeInsets.all(15.w)),
        ],
      ),
    );
  }

  //写一个listview的滑动鉴定
  ScrollController controller = ScrollController();

  //电影详情model
  MovieDetailEntity detailEntity = MovieDetailEntity();

  //电影的评论列表
  MovieCommnetsEntity commnetsEntity = MovieCommnetsEntity();

  double opac = 0;

  ChewieController chewieController =
      VideoController.getVideoControllerForMovieDetail("http://");

  getData() async {
    dynamic jsonData = await Api.getMovieDetail({'movieId': widget.movieId});
    Map<String, dynamic> resutl = Map.from(jsonData);

    dynamic jsonComments =
        await Api.getCommentList({'movieId': widget.movieId});
    Map<String, dynamic> result2 = Map.from(jsonComments);

    setState(() {
      detailEntity = MovieDetailEntity.fromJson(resutl);
      chewieController = VideoController.getVideoControllerForMovieDetail(
          detailEntity.item.movieUrl);
      commnetsEntity = MovieCommnetsEntity.fromJson(result2);
    });
  }

  ///
  /// 点赞
  ///
  onClickZan() async {
    dynamic result =
        await Api.postLikes({"movieId": detailEntity.item.movieId});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 200) {
      EasyLoading.showToast("点赞成功");
      setState(() {
        detailEntity.item.counts = detailEntity.item.counts += 1;
      });
    }
  }

  ///
  /// 收藏
  ///
  onClickCollect() async {
    String isCo = detailEntity.item.iscollec;
    String type = "1";
    if (isCo == "1") {
      type = "2"; //取消收藏
    } else {
      type = "1"; //收藏
    }
    dynamic result = await Api.postCollect(
        {"movieId": detailEntity.item.movieId, "type": type});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 200) {
      setState(() {
        if (isCo == "1") {
          detailEntity.item.iscollec = "0";
          EasyLoading.showToast("取消收藏成功");
        } else {
          detailEntity.item.iscollec = "1";
          EasyLoading.showToast("收藏成功");
        }
      });
    }
  }

  ///
  /// 评论
  ///
  onClicComment() {
    Routes.navigateTo(context, Routes.moviePostComment,
        params: {'movieId': detailEntity.item.movieId}).then((value) {
      if (value != null && value['result'] == 1) {
        getData();
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller.addListener(() {
      // if (controller.offset / 200 > 1) {
      //   return;
      // }
      // setState(() {
      //   opac = controller.offset / 200;
      // });
      // LogUtil.v(opac);
    });
    getData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose();
    chewieController.pause();
    chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          width: double.infinity,
          color: Config.colorBg,
          height: double.infinity,
          child: Stack(
            children: [
              ListView(
                controller: controller,
                padding: const EdgeInsets.all(0),
                children: [
                  //视频
                  SizedBox(
                    width: double.infinity,
                    height: 400.w,
                    child: Chewie(controller: chewieController),
                  ),
                  //电影信息
                  Container(
                    padding: EdgeInsets.fromLTRB(24.w, 24.w, 24.w, 0.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(3),
                          child: Image.network(
                            '${Config.baseUrl}${detailEntity.item.cover}',
                            fit: BoxFit.fill,
                            width: 230.w,
                            height: 320.w,
                          ),
                        ),
                        Padding(padding: EdgeInsets.all(10.w)),
                        SizedBox(
                          height: 350.w,
                          width: 450.w,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(detailEntity.item.movieName,
                                  style: TextStyle(
                                      color: (Config.colorText1),
                                      fontSize: 32.sp)),
                              Padding(padding: EdgeInsets.all(9.w)),
                              Text(
                                detailEntity.item.info,
                                style: TextStyle(
                                    color: (Config.colorText1),
                                    fontSize: 25.sp),
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                              Padding(padding: EdgeInsets.all(6.w)),
                              Text(
                                '时长：${detailEntity.item.totalTime}',
                                style: TextStyle(
                                    color: (Config.colorText1),
                                    fontSize: 25.sp),
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                              Padding(padding: EdgeInsets.all(6.w)),
                              Text(
                                '上映时间：${detailEntity.item.releaseDate}',
                                style: TextStyle(
                                    color: Config.colorText1, fontSize: 25.sp),
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                              Padding(padding: EdgeInsets.all(9.w)),
                              Container(
                                width: 400.w,
                                height: 100.w,
                                decoration: BoxDecoration(
                                    color: Config.colorMain,
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(3.w)),
                                    boxShadow: [
                                      BoxShadow(
                                          color: Config.colorDivider,
                                          blurRadius: 10.w,
                                          offset: Offset(4.w, 8.w))
                                    ]),
                                child: Row(
                                  children: [
                                    Container(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 20.w),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            '综合评分：',
                                            style: TextStyle(
                                                color: Config.colorText1,
                                                fontSize: 20.sp),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          ),
                                          Padding(padding: EdgeInsets.all(3.w)),
                                          Text(
                                            detailEntity.item.score.toString(),
                                            style: TextStyle(
                                                color: Config.colorText1,
                                                fontSize: 24.sp),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          )
                                        ],
                                      ),
                                    ),
                                    Container(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 15.w),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          RatingBar.builder(
                                            itemSize: 10,
                                            initialRating: 8 / 2,
                                            minRating: 1,
                                            direction: Axis.horizontal,
                                            allowHalfRating: true,
                                            itemCount: 5,
                                            ignoreGestures: true,
                                            itemPadding:
                                                const EdgeInsets.symmetric(
                                                    horizontal: 1.0),
                                            itemBuilder: (context, _) =>
                                                const Icon(
                                              Icons.star,
                                              color: Colors.orange,
                                            ),
                                            onRatingUpdate: (double value) {},
                                          ),
                                          Padding(padding: EdgeInsets.all(5.w)),
                                          Text(
                                            '${detailEntity.item.counts}人点赞',
                                            style: TextStyle(
                                                color: Config.colorText1,
                                                fontSize: 20.sp),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Divider(
                    color: Config.colorDivider,
                    height: 2.w,
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(24.w, 24.w, 24.w, 0.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '剧情介绍',
                          style: TextStyle(
                              color: (Config.colorText3), fontSize: 28.sp),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                        Padding(padding: EdgeInsets.all(3.w)),
                        Text(
                          detailEntity.item.plotDesc,
                          style: TextStyle(
                              color: (Config.colorText1), fontSize: 25.sp),
                        ),
                        Padding(padding: EdgeInsets.all(13.w)),
                        Text(
                          '演职人员',
                          style: TextStyle(
                              color: (Config.colorText3), fontSize: 28.sp),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                        Padding(padding: EdgeInsets.all(9.w)),
                        Container(
                          height: 340.w,
                          child: ListView.builder(
                              itemCount: detailEntity.item.plotsWords.length,
                              padding: const EdgeInsets.symmetric(
                                  vertical: 0, horizontal: 0),
                              shrinkWrap: true,
                              scrollDirection: Axis.horizontal,
                              physics: const BouncingScrollPhysics(),
                              itemBuilder: (context, index) {
                                return getYanyuan(index);
                              }),
                        ),
                        Padding(padding: EdgeInsets.all(13.w)),
                        Text(
                          '剧照',
                          style: TextStyle(
                              color: (Config.colorText3), fontSize: 28.sp),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                        Padding(padding: EdgeInsets.all(9.w)),
                        Container(
                          height: 340.w,
                          child: ListView.builder(
                              itemCount: detailEntity.item.plotsImg.length,
                              padding: const EdgeInsets.symmetric(
                                  vertical: 0, horizontal: 0),
                              shrinkWrap: true,
                              scrollDirection: Axis.horizontal,
                              physics: const BouncingScrollPhysics(),
                              itemBuilder: (context, index) {
                                return getJuzhao(index);
                              }),
                        ),
                        Padding(padding: EdgeInsets.all(10.w)),
                        Text(
                          '热门评论',
                          style: TextStyle(
                              color: (Config.colorText3), fontSize: 28.sp),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                        Padding(padding: EdgeInsets.all(15.w)),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              width: double.infinity,
                              child: ListView.builder(
                                itemCount: commnetsEntity.list.length,
                                padding: const EdgeInsets.symmetric(
                                    vertical: 0, horizontal: 5),
                                shrinkWrap: true,
                                scrollDirection: Axis.vertical,
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (BuildContext context, int index) {
                                  return getCommentList(index);
                                },
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  )
                ],
              ),
              Positioned(
                right: 30.w,
                bottom: 30.w,
                child: Opacity(
                  opacity: 0.9,
                  child: Container(
                    width: 75.w,
                    height: 230.w,
                    decoration: BoxDecoration(
                        color: Config.colorMain,
                        borderRadius: BorderRadius.all(Radius.circular(10.w)),
                        boxShadow: [
                          BoxShadow(
                              color: Config.colorDivider,
                              blurRadius: 10.w,
                              offset: Offset(4.w, 8.w))
                        ]),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        InkWell(
                          onTap: () {
                            onClickZan();
                          },
                          child: Icon(
                            Icons.thumb_up,
                            color: Colors.white,
                            size: 38.w,
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            onClickCollect();
                          },
                          child: Icon(
                            detailEntity.item.iscollec == '0'
                                ? Icons.sentiment_neutral
                                : Icons.sentiment_satisfied_alt_sharp,
                            color: Colors.white,
                            size: 38.w,
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            onClicComment();
                          },
                          child: Icon(
                            Icons.comment,
                            color: Colors.white,
                            size: 38.w,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Opacity(
                // opacity: opac,
                opacity: 1,
                child: Container(
                  width: double.infinity,
                  height: 133.w,
                  decoration: const BoxDecoration(color: Colors.transparent),
                  padding: EdgeInsets.fromLTRB(20.w, 38.w, 20.w, 0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        onTap: () {
                          Routes.router.pop(context);
                        },
                        child: const Icon(
                          Icons.arrow_back,
                          color: Config.colorText1,
                        ),
                      ),
                      const Text(
                        "",
                        maxLines: 1,
                        style: TextStyle(color: Colors.white),
                      ),
                      const Opacity(
                        opacity: 0,
                        child: Icon(
                          Icons.arrow_back,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          )),
    );
  }
}
